import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { Role } from './user/entities/role.entity';
import { Reflector } from '@nestjs/core';

//因为 typescript 里同名 module 和 interface 会自动合并，可以这样扩展类型。
declare module 'express' {
  interface Request {
    user: {
      username: string;
      roles: Role[]
    }
  }
}


@Injectable()
export class LoginGuard implements CanActivate {
  
  @Inject(JwtService)
  private jwtService: JwtService;

  @Inject(Reflector)
  reflector: Reflector;
  
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {

    const request: Request = context.switchToHttp().getRequest();
  
    //先获取类级别（context.getClass()）的装饰器值，然后再获取方法级别（context.getHandler()）的装饰器值。如果多个装饰器被应用在类或方法上，那么这个方法会返回一个数组，包含这些装饰器的值。如果装饰器没有被应用在类或方法上，则返回 undefined。
    const requireLogin = this.reflector.getAllAndOverride('require-login',[
      context.getClass(),
      context.getHandler()
    ])
    //获取指定装饰器的值,只返回第一个找到的装饰器的值,只获取方法级别的装饰器值
    // this.reflector.get('require-login', context.getHandler());


    if(!requireLogin) {
      return true;
    }

    const authorization = request.headers.authorization;

    if(!authorization) {
      throw new UnauthorizedException('用户未登录');
    }

    try{
      const token = authorization.split(' ')[1];
      const data = this.jwtService.verify(token);

      request.user = data.user;
      return true;
    } catch(e) {
      throw new UnauthorizedException('token 失效，请重新登录');
    }
    
  }
}
